using Aliphant.Mvvm.XEvent.UI;
using GrpcClient.Managers;
using GrpcClient.Models;
using Microsoft.Web.WebView2.Core;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace GrpcClient.UI
{
    /// <summary>
    /// WebViewControl.xaml 的交互逻辑
    /// </summary>
    public partial class WebViewControl : UserControl
    {
        private bool isLoad = false;
        public string Id { get; set; } = Guid.NewGuid().ToString();


        public string WebTitle
        {
            get { return (string)GetValue(WebTitleProperty); }
            set
            {
                SetValue(WebTitleProperty, value);
            }
        }

        // Using a DependencyProperty as the backing store for WebTitle.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty WebTitleProperty =
            DependencyProperty.Register("WebTitle", typeof(string), typeof(WebViewControl));



        public WebViewControl()
        {
            InitializeComponent();
        }

        public async Task Load()
        {
            if (!isLoad)
            {
                isLoad = true;
                await OnLoad();
            }
        }

        private async void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (!isLoad)
            {
                isLoad = true;
                await OnLoad();
            }
        }

        private async Task OnLoad()
        {
            if (webView.CoreWebView2 == null)
            {
                await webView.EnsureCoreWebView2Async().ContinueWith(_ =>
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        webView.SourceChanged += WebView_SourceChanged;
                        webView.CoreWebView2.NavigationCompleted += CoreWebView2_NavigationCompleted;
                    });
                });
                webView.CoreWebView2.NewWindowRequested += OnNewWindowRequest;
            }
        }

        private void WebView_SourceChanged(object? sender, CoreWebView2SourceChangedEventArgs e)
        {
            WebTitle = webView.CoreWebView2.DocumentTitle;
            TabManager.Instance.UpdateInputUrl(webView.CoreWebView2.Source);
        }

        private async void OnNewWindowRequest(object? sender, CoreWebView2NewWindowRequestedEventArgs e)
        {
            var deferral = e.GetDeferral();
            var newView = TabManager.Instance.Create();
            await newView.Load();

            e.NewWindow = newView.webView.CoreWebView2;
            deferral.Complete();
        }

        private void CoreWebView2_NavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e)
        {
            if (e.IsSuccess)
            {
                WebTitle = webView.CoreWebView2.DocumentTitle;
                TabManager.Instance.UpdateInputUrl(webView.CoreWebView2.Source);
            }
        }

        public ICommand CloseCommand
        {
            get => new RelayCommand<object>(obj =>
            {
                TabManager.Instance.Remove(Id);
            });
        }

        public ICommand CollectionCommand
        {
            get => new RelayCommand<object>(obj =>
            {
                var models = ConfigContainer.Instance.cacheManager.Get<List<NavigateWebModel>>("apps");
                if (models != null)
                {
                    var source = webView.CoreWebView2.Source;
                    models.Add(new NavigateWebModel
                    {
                        Name = this.WebTitle,
                        ViewName = "webview",
                        WebUri = source
                    });
                    MessageBox.Show("收藏成功");
                }
                ConfigContainer.Instance.cacheManager.Update("apps", models);
            });
        }


    }
}
